//
//  WithdrawVC.swift
//  LeTu
//
//  Created by g1 on 2024/1/4.
//

import UIKit
import BUAdSDK

class WithdrawVC: BaseViewController {
    
    private var viewModel = WithdrawVM()
    private var balance = ""
    private var currentSelect = 0
    
    // 信息广告
    private var nativeAd: BUNativeAdsManager?
    private var adView: BUMCanvasView?
    private var adViewHeight: CGFloat = 180
    
    init(balance: String) {
        self.balance = balance
        super.init()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        configUI()
        getAdData()

    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        getUserInfo()
        getWithdrawPrices()
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        DispatchQueue.main.async {
            self.withdrawBtn.layerCornerRadius(self.withdrawBtn.height/2)
        }
    }
    // 获取用户信息
    private func getUserInfo() {
        
        kUserManager.getUserInfomation { [weak self] dialog in
            guard let strongSelf = self else { return }
            DispatchQueue.main.async {
                strongSelf.withdrawBtn.setTitle(kUserManager.userModel.openid.count > 0 ? "去提现".localized:"去微信绑定".localized)
                strongSelf.withdrawTableView.reloadSections([0], with: .none)
            }
        }
        
    }
    // 获取提现金额列表
    private func getWithdrawPrices() {
        viewModel.getWithdrawPrices { [weak self] dialog in
            guard let strongSelf = self else { return }
            DispatchQueue.main.async {
                strongSelf.withdrawTableView.reloadSections([0], with: .none)
            }
        }
    }
    
    // MARK: - UIButtonAction
    // 点击提现按钮
    @objc private func withdrawBtnAction() {
        
        if withdrawBtn.title == "去微信绑定".localized {
            selectPlatform()
        } else {
            let priceModel = viewModel.pricesArr[currentSelect]
            let affirmInfoAlertView = WithdrawAffirmInfoAlertView(price: "\(priceModel.money)", platformType: .wechat)
            affirmInfoAlertView.toWidthdrawHandle = { [weak self] platform in
                guard let strongSelf = self else { return }
                strongSelf.withdraw()
            }
            affirmInfoAlertView.show()
            
        }
        
    }
    // 提现
    private func withdraw() {
        
        let priceModel = viewModel.pricesArr[currentSelect]
        guard (Float(balance) ?? 0) > Float(priceModel.money) else { return showMessage(message: "余额不足".localized) }
        showIndicator()
        viewModel.withdrawWechat(money: priceModel.money) { [weak self] dialog in
            guard let strongSelf = self else { return }
            strongSelf.hideIndicator()
            DispatchQueue.main.async {
                if dialog.code == 200 {
                    
                    // 提示提现成功
                    let commitSuccesAlertView = OrderCommitSuccessBottomAlertView(platformType: .wechat)
                    commitSuccesAlertView.show()
                    
                    strongSelf.getUserInfo()
                }
                strongSelf.showMessage(message: dialog.message)
            }
        }
        
    }
    
    // MARK: - configUI
    func configUI() {
        
        navIsHidden = false
        title = "提现".localized
        
        view.addSubview(withdrawBtn)
        view.addSubview(withdrawTableView)
        
        withdrawBtn.snp.makeConstraints { make in
            make.left.equalTo(22)
            make.right.equalTo(-22)
            make.bottom.equalTo(-(iPhoneX ? Size.safeAreaBottomGap : 20)-10)
            make.height.equalTo(CGFloat.app_btnHeight)
        }
        withdrawTableView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.bottom.equalTo(withdrawBtn.snp.top).offset(-12)
        }
        
        withdrawBtn.addTarget(self, action: #selector(withdrawBtnAction))
        withdrawTableView.delegate = self
        withdrawTableView.dataSource = self
        withdrawTableView.register(cellClass: WithdrawTableViewCell.self)
        withdrawTableView.register(cellClass: EarningsAdTableViewCell.self)
        
    }
    private var withdrawTableView: UITableView = {
        let withdrawTableView = UITableView()
        withdrawTableView.showsVerticalScrollIndicator = false
        withdrawTableView.tableFooterView = UIView()
        return withdrawTableView
    }()
    private lazy var withdrawBtn: GradientButton = {
        let withdrawBtn = GradientButton()
        withdrawBtn.gradientColors = UIColor.app_themeGradientColors
        withdrawBtn.setFont(kSetPingFangBlod(15))
        return withdrawBtn
    }()
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension WithdrawVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return section == 0 ? 28:0.01
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == 0 {
            let footerView = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: tableView.sectionFooterHeight))
            return footerView
        }
        return UIView()
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.section == 0 {
            return WithdrawTableViewCell.getCellHeight()
        }
        return adViewHeight

    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1 + (adView != nil ? 1:0)
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(WithdrawTableViewCell.self, indexPath: indexPath)
            cell.setInfo(balance: balance, pricesArr: viewModel.pricesArr)
            cell.updatePlateformBindStatus(kUserManager.userModel.openid.count > 0 ? kUserManager.userModel.wxName:"未绑定账号".localized)
            cell.selectHandle = { [weak self] index in
                guard let strongSelf = self else { return }
                strongSelf.currentSelect = index
            }
            return cell
        }
        let cell = tableView.dequeueReusableCell(EarningsAdTableViewCell.self, indexPath: indexPath)
        cell.setAdView(adView!)
        return cell
        
    }
        
}

extension WithdrawVC: TransferEventReceivable {
    
    enum TransferEvent: TransferEventType {
        case clickPlatform
    }
    
    func receive(event: TransferEventType) {
        switch event {
        case WithdrawVC.TransferEvent.clickPlatform:
            selectPlatform()
        default:
            break
        }
    }
    
    // 点击平台信息
    @objc private func selectPlatform() {
        
        if kUserManager.userModel.openid.count == 0 { // 绑定三方平台
            let platformItem = PlatformItem(type: .wechat, icon: "platform_wechat", title: "绑定微信号".localized, details: "为了您的资金安全，需前往微信授权绑定之后才能提现，只需绑定一次，后续均提现至该微信账号。".localized)
            let bindAlertView = BindPlatformBottomAlertView(platform: platformItem)
            bindAlertView.toBindHandle = { [weak self] platformType in
                guard let strongSelf = self else { return }
                strongSelf.bindPlatfrom(type: platformType)
            }
            bindAlertView.show()
        } else { // 解除绑定三方平台
            let unBindAlertView = UnBindPlatformBottomAlertView(platformType: .wechat)
            unBindAlertView.toUnBindHandle = { [weak self] platformType in
                guard let strongSelf = self else { return }
                strongSelf.viewModel.unBindWX { [weak self] dialog in
                    guard let strongSelf = self else { return }
                    DispatchQueue.main.async {
                        if dialog.code == 200 {
                            strongSelf.getUserInfo()
                        } else {
                            strongSelf.showMessage(message: dialog.message)
                        }
                    }
                }
                
            }
            unBindAlertView.show()
        }
        
    }
    
    // 绑定 支付 平台
    private func bindPlatfrom(type: PayPlatformType) {
        switch type {
        case .wechat:
            kUMengManager.um_login(platformType: .wechatSession, currentVC: self) { [weak self] result, error in
                
                guard let strongSelf = self, let resp = result as? UMSocialUserInfoResponse else { return } // let wechatUserJson = resp.yy_modelToJSONString()
                let param: [String: Any] = ["openId": resp.openid!, "wxName": resp.name!]
                strongSelf.viewModel.bindWx(params: param) { [weak self] dialog in
                    guard let strongSelf = self else { return }
                    DispatchQueue.main.async {
                        if dialog.code == 200 {
                            strongSelf.getUserInfo()
                        } else {
                            strongSelf.showMessage(message: dialog.message)
                        }
                    }
                }
            }
        case .ali:
            break
        }
        
    }
    
}

// MARK: - 加载开屏广告
extension WithdrawVC: BUNativeAdsManagerDelegate, BUNativeAdDelegate {
    
    // 加载广告信息
    private func getAdData() {
        
        if let ad = nativeAd {
            /// 销毁上次信息流广告对象
            kAdsManager.destoryNativeExpressAdManager(ad)
        }
        
        nativeAd = kAdsManager.loadNativeExpressTheAdvertising(adSize: EarningsAdTableViewCell.getEarningsAdCellHeight(), vc: self, delegate: self)
        if nativeAd != nil {
            nativeAd?.loadAdData(withCount: 1)
        } else {
            kAdsManager.requestAdsIdList { [weak self] dialog in
                guard let strongSelf = self else { return }
                DispatchQueue.main.async {
                    strongSelf.nativeAd = kAdsManager.loadNativeExpressTheAdvertising(adSize: CGSize(width: screenWidth, height: 180), vc: strongSelf, delegate: strongSelf)
                    strongSelf.nativeAd?.loadAdData(withCount: 1)
                }
            }
        }
        
    }
    
    func nativeAdsManagerSuccess(toLoad adsManager: BUNativeAdsManager, nativeAds nativeAdDataArray: [BUNativeAd]?) {
        guard let list = nativeAdDataArray else { return }
        
        var adViews = [BUMCanvasView]()
        for model in list {
            model.rootViewController = self
            model.delegate = self
            if let isExpressAd = model.mediation?.isExpressAd {
                model.mediation?.render()
            }
            /*
            //  (注意: getShowEcpmInfo 只需要在当前 adView show 之后调用, show 之前调用该方法会返回 nil)
            let info = model.mediation?.getShowEcpmInfo()
            MYLog("ecpm:\(info?.ecpm ?? "None")")
            MYLog("platform:\(info?.adnName ?? "None")")
            MYLog("ritID:\(info?.slotID ?? "None")")
            MYLog("requestID:\(info?.requestID ?? "None")")
            */

            if let mediaExt = model.mediation?.extraData() {
                MYLog("coupon:\(mediaExt["coupon"] ?? "nil")")
                MYLog("live_room:\(mediaExt["live_room"] ?? "nil")")
                MYLog("product:\(mediaExt["product"] ?? "nil")")
            }

            // 展示广告
            if let canvasView = model.mediation?.canvasView {
                adViews.append(canvasView)
                adViewHeight = canvasView.bounds.size.height
            }
        }
        
        if adView != nil && adViews.first != nil {
            adView?.removeFromSuperview()
        }
        adView = adViews.first
        withdrawTableView.reloadData()
        
    }
    
}




